<template>
  <div
      class="diy_edit customized_products_edits page_customized_products"
      id="customized_products_edit"
  >
    <el-form
        :model="form"
        ref="ruleFormRef" 
		:rules="rules"
        label-width="auto"
        class="edit_customized_products_form"
        size="large"
    >
      <el-row class="row_e">
          <el-col v-if="$check_field('ger','product_number','/customized_products/view') || $check_field('add','product_number','/customized_products/view') || $check_field('set','product_number','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="商品编号" prop="product_number">
                      <el-input id="product_number" v-model="form['product_number']" placeholder="请输入商品编号"
                      v-if="(form['customized_products_id'] && $check_field('set','product_number','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','product_number','/customized_products/view'))" :disabled="true"></el-input>
            <div v-else-if="$check_field('ger','product_number','/customized_products/view')">{{form['product_number']}}</div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','product_name','/customized_products/view') || $check_field('add','product_name','/customized_products/view') || $check_field('set','product_name','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="商品名称" prop="product_name">
                      <el-input id="product_name" v-model="form['product_name']" placeholder="请输入商品名称"
                      v-if="(form['customized_products_id'] && $check_field('set','product_name','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','product_name','/customized_products/view'))" :disabled="disabledObj['product_name_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','product_name','/customized_products/view')">{{form['product_name']}}</div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','classification_name','/customized_products/view') || $check_field('add','classification_name','/customized_products/view') || $check_field('set','classification_name','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="分类名称" prop="classification_name">
                <el-select id="classification_name" v-model="form['classification_name']"                       v-if="(form['customized_products_id'] && $check_field('set','classification_name','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','classification_name','/customized_products/view'))">
              <el-option v-for="o in list_classification_name" :key="o['classification_name']" :label="o['classification_name']"
                         :value="o['classification_name']">
              </el-option>
            </el-select>
            <div v-else-if="$check_field('ger','classification_name','/customized_products/view')">{{form['classification_name']}}</div>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','product_cover','/customized_products/view') || $check_field('add','product_cover','/customized_products/view') || $check_field('set','product_cover','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="商品封面" prop="product_cover">
                <el-upload :disabled="disabledObj['product_cover_isDisabled']" class="avatar-uploader" drag
                       accept="image/gif, image/jpeg, image/png, image/jpg" action="" :http-request="upload_product_cover"
                       :show-file-list="false" v-if="(form['customized_products_id'] && $check_field('set','product_cover','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','product_cover','/customized_products/view'))">
              <img id="product_cover" v-if="form['product_cover']" :src="$fullUrl($banseUrl,form['product_cover'])" class="avatar">
              <el-icon v-else><Plus /></el-icon>
            </el-upload>
            <el-image v-else-if="$check_field('ger','product_cover','/customized_products/view')" style="width: 100px; height: 100px"
                      :src="$fullUrl(form['product_cover'])" :preview-src-list="[$fullUrl(form['product_cover'])]">
              <div slot="error" class="image-slot">
                <img src="../../assets/images/user.png" style="width: 90px; height: 90px" />
              </div>
            </el-image>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','album','/customized_products/view') || $check_field('add','album','/customized_products/view') || $check_field('set','album','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="商品相册" prop="album">
                      <el-input id="album" v-model="form['album']" placeholder="请输入商品相册"
                      v-if="(form['customized_products_id'] && $check_field('set','album','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','album','/customized_products/view'))" :disabled="disabledObj['album_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','album','/customized_products/view')">{{form['album']}}</div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','customized_inventory','/customized_products/view') || $check_field('add','customized_inventory','/customized_products/view') || $check_field('set','customized_inventory','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="定制库存" prop="customized_inventory">
                <el-input-number id="customized_inventory" v-model.number="form['customized_inventory']"
                             v-if="(form['customized_products_id'] && $check_field('set','customized_inventory','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','customized_inventory','/customized_products/view'))" :disabled="disabledObj['customized_inventory_isDisabled']"></el-input-number>
            <div v-else-if="$check_field('ger','customized_inventory','/customized_products/view')">{{form['customized_inventory']}}</div>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','production_date','/customized_products/view') || $check_field('add','production_date','/customized_products/view') || $check_field('set','production_date','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="生产日期" prop="production_date">
                <el-date-picker :disabled="disabledObj['production_date_isDisabled']" v-if="(form['customized_products_id'] && $check_field('set','production_date','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','production_date','/customized_products/view'))" id="production_date"
                            v-model="form['production_date']" type="date" placeholder="选择日期">
            </el-date-picker>
            <div v-else-if="$check_field('ger','production_date','/customized_products/view')">{{form['production_date']}}</div>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','merchant_users','/customized_products/view') || $check_field('add','merchant_users','/customized_products/view') || $check_field('set','merchant_users','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="商家用户" prop="merchant_users">
                              <div v-if="user_group !== '管理员'">
              {{ get_user_session_merchant_users(form['merchant_users']) }}
              <el-select v-if="(form['customized_products_id'] && $check_field('set','merchant_users','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','merchant_users','/customized_products/view'))" id="merchant_users" v-model="form['merchant_users']" :disabled="disabledObj['merchant_users_isDisabled']">
                <el-option v-for="o in list_user_merchant_users" :key="o['username']" :label="o['nickname'] + '-' + o['username']"
                           :value="o['user_id']">
                </el-option>
              </el-select>
              <el-select v-else-if="$check_field('ger','merchant_users','/customized_products/view')" id="merchant_users" v-model="form['merchant_users']" :disabled="true">
                <el-option v-for="o in list_user_merchant_users" :key="o['username']" :label="o['nickname'] + '-' + o['username']"
                           :value="o['user_id']">
                </el-option>
              </el-select>
            </div>
            <el-select v-else id="merchant_users" v-model="form['merchant_users']" :disabled="disabledObj['merchant_users_isDisabled']">
              <el-option v-for="o in list_user_merchant_users" :key="o['username']" :label="o['nickname'] + '-' + o['username']"
                         :value="o['user_id']">
              </el-option>
            </el-select>
                                  </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','shelf_life','/customized_products/view') || $check_field('add','shelf_life','/customized_products/view') || $check_field('set','shelf_life','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="保质时间" prop="shelf_life">
                <el-date-picker :disabled="disabledObj['shelf_life_isDisabled']" v-if="(form['customized_products_id'] && $check_field('set','shelf_life','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','shelf_life','/customized_products/view'))" id="shelf_life"
                            v-model="form['shelf_life']" type="datetime" placeholder="选择日期时间">
            </el-date-picker>
            <div v-else-if="$check_field('ger','shelf_life','/customized_products/view')">{{form['shelf_life']}}</div>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','customized_declaration','/customized_products/view') || $check_field('add','customized_declaration','/customized_products/view') || $check_field('set','customized_declaration','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="定制声明" prop="customized_declaration">
                      <div v-if="disabledObj['customized_declaration_isDisabled']">
              <div v-if="$check_field('ger','customized_declaration','/customized_products/view')">
                <el-button type="primary" @click="$download($fullUrl(form['customized_declaration']),form['customized_declaration'])">下载<i
                        class="el-icon-download el-icon--right"></i></el-button>
              </div>
            </div>
            <div v-else>
              <el-upload v-if="(form['customized_products_id'] && $check_field('set','customized_declaration','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','customized_declaration','/customized_products/view'))" class="upload-demo" drag
                         action="" style="max-width: 300px;width: 100%;" :http-request="upload_customized_declaration" accept="">
                <el-icon><Plus /></el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
              <div v-else-if="$check_field('ger','customized_declaration','/customized_products/view')">
                <el-button type="primary" @click="$download($fullUrl($banseUrl,form['customized_declaration']),form['customized_declaration'])">下载<i
                        class="el-icon-download el-icon--right"></i></el-button>
              </div>
            </div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','customized_types','/customized_products/view') || $check_field('add','customized_types','/customized_products/view') || $check_field('set','customized_types','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="定制类型" prop="customized_types">
                <el-select id="customized_types" v-model="form['customized_types']" @change="select_customized_types_field"                       v-if="(form['customized_products_id'] && $check_field('set','customized_types','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','customized_types','/customized_products/view'))">
              <el-option v-for="o in list_customized_types" :key="o['classification_name']" :label="o['classification_name']"
                         :value="o['classification_name']">
              </el-option>
            </el-select>
            <div v-else-if="$check_field('ger','customized_types','/customized_products/view')">{{form['customized_types']}}</div>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','customization_requirements','/customized_products/view') || $check_field('add','customization_requirements','/customized_products/view') || $check_field('set','customization_requirements','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="定制要求" prop="customization_requirements">
                <el-select id="customization_requirements" v-model="customization_requirements_multiple_value" multiple @change="select_customization_requirements_multiple"
                       v-if="(form['customized_products_id'] && $check_field('set','customization_requirements','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','customization_requirements','/customized_products/view'))">
              <el-option v-for="o in list_customization_requirements" :key="o['classification_name']" :label="o['classification_name']"
                         :value="o['classification_name']">
              </el-option>
            </el-select>
            <div v-else-if="$check_field('ger','customization_requirements','/customized_products/view')">{{form['customization_requirements']}}</div>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','customized_pricing','/customized_products/view') || $check_field('add','customized_pricing','/customized_products/view') || $check_field('set','customized_pricing','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="定制价格" prop="customized_pricing">
                <el-input id="customized_pricing" v-model="form['customized_pricing']"
                      v-if="(form['customized_products_id'] && $check_field('set','customized_pricing','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','customized_pricing','/customized_products/view'))" :disabled="true"></el-input>
            <div v-else-if="$check_field('ger','customized_pricing','/customized_products/view')">{{form['customized_pricing']}}</div>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','explanation_remarks','/customized_products/view') || $check_field('add','explanation_remarks','/customized_products/view') || $check_field('set','explanation_remarks','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="说明备注" prop="explanation_remarks">
                <el-input type="textarea" id="explanation_remarks" v-model="form['explanation_remarks']" placeholder="请输入说明备注"
                      v-if="(form['customized_products_id'] && $check_field('set','explanation_remarks','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','explanation_remarks','/customized_products/view'))" :disabled="disabledObj['explanation_remarks_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','explanation_remarks','/customized_products/view')">{{form['explanation_remarks']}}</div>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','product_details','/customized_products/view') || $check_field('add','product_details','/customized_products/view') || $check_field('set','product_details','/customized_products/view')" :xs="24" :sm="24" :lg="24" class="el_form_editor_warp">
			<el-form-item label="商品详情" prop="product_details">
            <form_editor
                    v-if="(form['customized_products_id'] && $check_field('set','product_details','/customized_products/view')) || (!form['customized_products_id'] && $check_field('add','product_details','/customized_products/view')) "
                    class="editor el_form_editor_warp"
                    :details='form.product_details'
                    :form="form"
                    @blur_comment="blur_product_details"
                    @update_comment="update_product_details"
                    :publish_flag="false"
            />
            <div v-else-if="$check_field('ger','product_details','/customized_products/view')" v-html="form['product_details']"></div>
          </el-form-item>
        </el-col>
          <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="审核状态" prop="examine_state">
            <el-select id="examine_state" v-model="form['examine_state']"
                       v-if="(form['examine_state'] && $check_option('/customized_products/table','examine')) || (!form['examine_state'] && $check_option('/customized_products/table','examine'))">
              <el-option key="未审核" label="未审核" value="未审核"></el-option>
              <el-option key="已通过" label="已通过" value="已通过"></el-option>
              <el-option key="未通过" label="未通过" value="未通过"></el-option>
            </el-select>
            <div v-else>{{form["examine_state"]}}</div>
          </el-form-item>
        </el-col>

            <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
            <el-form-item label="二维码图片" prop="qrcode_img">
              <el-upload :disabled="disabledObj['qrcode_img_isDisabled']" id="qrcode_img" class="avatar-uploader" drag
                  accept="image/gif, image/jpeg, image/png, image/jpg" action="" :http-request="upload_qrcode" :show-file-list="false">
                <img v-if="form['qrcode_img']" :src="$fullUrl($banseUrl, form['qrcode_img'])" class="avatar"/>
                <el-icon v-else><Plus /></el-icon>
              </el-upload>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
            <el-form-item label="二维码标题" prop="qrcode_title">
              <el-input id="qrcode_title" v-model="form['qrcode_title']" placeholder="请输入二维码标题" :disabled="disabledObj['qrcode_title_isDisabled']"></el-input>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
            <el-form-item label="计时器标题" prop="timer_title">
              <el-input id="timer_title" v-model="form['timer_title']" placeholder="请输入计时器标题"
                  v-if="$check_action('/customized_products/view', 'set') || $check_action('/customized_products/view', 'add')" :disabled="disabledObj['timer_title_isDisabled']"></el-input>
              <div v-else-if="$check_field('get', 'timer_title')">
                {{ form["timer_title"] }}
              </div>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
            <el-form-item label="计时开始时间" prop="timing_start_time">
              <el-date-picker id="timing_start_time" v-model="form['timing_start_time']" placeholder="选择计时器开始时间"
                  v-if="$check_action('/customized_products/view', 'set') || $check_action('/customized_products/view', 'add')"
                  :disabled="disabledObj['timing_start_time_isDisabled']" type="datetime">
              </el-date-picker>
              <div v-else-if="$check_field('get', 'timing_start_time')">
                {{ form["timing_start_time"] }}
              </div>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
            <el-form-item label="计时结束时间" prop="timing_end_time">
              <el-date-picker id="timing_end_time" v-model="form['timing_end_time']" placeholder="选择计时器开始时间"
                  v-if="$check_action('/customized_products/view', 'set') || $check_action('/customized_products/view', 'add')"
                  :disabled="disabledObj['timing_end_time_isDisabled']" type="datetime">
              </el-date-picker>
              <div v-else-if="$check_field('get', 'timing_end_time')">
                {{ form["timing_end_time"] }}
              </div>
            </el-form-item>
        </el-col>
        <el-col v-if="$check_action('/customized_products/view', 'set') || $check_action('/customized_products/view', 'add')"
          :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
            <el-form-item label="当前位置" prop="location_address">
              <el-input style="width: 80%" id="location_address" v-model="form['location_address']" :disabled="true"></el-input>
              <el-button size="mini" @click="getLongitudeLatitude()">定位</el-button>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
            <el-form-item label="限制次数" prop="limit_times">
              <el-input id="limit_times" v-model="form['limit_times']" placeholder="限制次数"
                  v-if="(form['customized_products_id}'] && $check_action('/customized_products/view', 'set')) || (!form['customized_products_id}'] && $check_action('/customized_products/view', 'add'))"></el-input>
              <div v-else-if="$check_action('/customized_products/view', 'get')" v-html="form['limit_times']"></div>
            </el-form-item>
        </el-col>
      </el-row>
      <div v-if="$check_action('/customized_products/view','set') || $check_action('/customized_products/view','add') || $check_option('/customized_products/table','examine')" class="footer">
        <el-button type="primary" @click="onSubmit" size="large">提交</el-button>
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
      <div v-else class="footer">
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
  import {ElMessage} from "element-plus";
  import {ref, onMounted} from "vue";
  import { $post, $get } from "@/api/Api.js";
  import storageHelper from "@/libs/StorageHelper";
  import {useStore} from "vuex";
  import { useRouter, useRoute } from "vue-router";
  import {
          $check_field,
          $fullUrl,
          $banseUrl,
          $check_action,
          $getUrlParams,
          filterSensitiveWords,
          $get_stamp,
          $get_rand,
          $toTime,
          $push
  } from "@/utils/utils.js";

  let router = useRouter();
  let route = useRoute();
  let store = useStore();
  let token = storageHelper.getToken() || null;
  let UserInfo = storageHelper.getUserInfo();
  let user_id = storageHelper.getUserInfo().user_id;
  let user_group = storageHelper.getUserInfo().user_group;
  let customized_products_id = $getUrlParams().customized_products_id;
  let url_add = ref("/api/customized_products/add");
  let url_set = ref("/api/customized_products/set");
  let field = ref("customized_products_id")
  let url_get_obj = ref("/api/customized_products/get_obj");
  let url_upload = ref("/api/customized_products/upload");
  let ruleFormRef = ref(null);
  
  let rules = ref({
															  });

  let disabledObj = ref({
      "product_number_isDisabled": false,
        "product_name_isDisabled": false,
        "classification_name_isDisabled": false,
        "product_cover_isDisabled": false,
        "album_isDisabled": false,
        "customized_inventory_isDisabled": false,
        "production_date_isDisabled": false,
        "merchant_users_isDisabled": false,
        "shelf_life_isDisabled": false,
        "customized_declaration_isDisabled": false,
        "customized_types_isDisabled": false,
        "customization_requirements_isDisabled": false,
        "customized_pricing_isDisabled": false,
        "explanation_remarks_isDisabled": false,
        "product_details_isDisabled": false,
      "qrcode_img_isDisabled": false,
    "qrcode_title_isDisabled": false,
    "timer_title_isDisabled": false,
    "timing_start_time_isDisabled": false,
    "timing_end_time_isDisabled": false,
    "limit_times_isDisabled": false, // 限制次数
  });
  let form = ref({
    "product_number": $get_stamp(), // 商品编号
      "product_name":  '', // 商品名称
      "classification_name":  '', // 分类名称
      "product_cover":  '', // 商品封面
      "album":  '', // 商品相册
      "customized_inventory":  0, // 定制库存
      "production_date":  '', // 生产日期
        "merchant_users": 0, // 商家用户
      "shelf_life":  '', // 保质时间
      "customized_declaration":  '', // 定制声明
      "customized_types":  '', // 定制类型
      "customization_requirements":  '', // 定制要求
      "customized_pricing":  '', // 定制价格
      "explanation_remarks":  '', // 说明备注
      "product_details":  '', // 商品详情
      "examine_state": "未审核",
    "customized_products_id": 0, // ID
    "qrcode_img":'', // 图片
    "qrcode_title":'', // 二维码标题
    "location_address": "", // 定位地址
    "location_lng": "", // 定位地址经度
    "location_lat": "", // 定位地址纬度
    "timer_title":'', // 计时器标题
    "timing_start_time":'', // 计时开始时间
    "timing_end_time":'', // 计时结束时间
    "limit_times": "", // 限制次数
      "limit_type":1,
    });
  
    
            // 分类名称选项列表
  let list_classification_name = ref([""]);
  
    
    
    
    
    
    // 用户列表
  let list_user_merchant_users = ref([]);
        // 用户组
  let group_user_merchant_users=ref({});
          
    
            // 定制类型选项列表
  let list_customized_types = ref([""]);
  
            let customization_requirements_multiple_value = ref([]);
        // 定制要求选项列表
  let list_customization_requirements = ref([""]);
  
    
    
    
                                                          //获取标签列表
    let get_list_classification_name = async () => {
      let json = await $get("/api/classification_information/get_list");
      if (json.result && json.result.list) {
        list_classification_name.value = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
    }
                                        /**
     * 上传商品封面
     * @param {Object} param 文件参数
     */
    let upload_product_cover=(param) =>{
        uploadFile(param.file, "product_cover");
    }
                                                                                                        //获取商家用户用户列表
    let get_list_user_merchant_users = async () => {
      let json = await $get("/api/user/get_list?user_group=商家用户");
      if (json.result) {
        list_user_merchant_users.value = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
    }
            //获取商城卖家用户组
    let get_group_user_merchant_users = async () => {
      let json = await $get("/api/user_group/get_obj?name=商家用户");
      if (json.result) {
        group_user_merchant_users.value = json.result.obj;
      } else if (json.error) {
        console.error(json.error);
      }
    }
    //获取
    let get_user_session_merchant_users = (id) => {
      let user_id = { user_id: id };
      let source_table = group_user_merchant_users.value.source_table
      if (source_table) {
        let url = "/api/" + source_table + "/get_obj"
        $get(url, {user_id: user_id}).then((res) => {
          if (res.result && res.result.obj) {
            var arr = []
            for (let key in res.result.obj) {
              arr.push(key)
            }
            var arrForm = []
            for (let key in form.value) {
              arrForm.push(key)
            }
            form.value["merchant_users"] = id
            disabledObj.value['merchant_users' + '_isDisabled'] = true
            for (var i = 0; i < arr.length; i++) {
              if (arr[i] !== 'examine_state' && arr[i] !== 'examine_reply') {
                for (var j = 0; j < arrForm.length; j++) {
                  if (arr[i] === arrForm[j]) {
                    if (arr[i] !== "merchant_users") {
                      form.value[arrForm[j]] = res.result.obj[arr[i]]
                      disabledObj.value[arrForm[j] + '_isDisabled'] = true
                      break;
                    } else {
                      disabledObj.value[arrForm[j] + '_isDisabled'] = true
                    }
                  }
                }
              }
            }
          }
        });
      }
    }
                                                /**
     * 上传定制声明
     * @param {Object} param 文件参数
     */
    let upload_customized_declaration=(param) =>{
        uploadFile(param.file, "customized_declaration");
    }
                                        //获取标签列表
    let get_list_customized_types = async () => {
      let json = await $get("/api/classification_information/get_list");
      if (json.result && json.result.list) {
        list_customized_types.value = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
    }
            //获取定制类型列表
    let select_customized_types_field = async (v) => {
      await $get("/api/classification_information/get_obj?classification_name=" + v).then((res) => {
        if (res.result && res.result.obj) {
                                                                                                                                                                                                                                                                                                                                                                                        form.value.customized_pricing = res.result.obj.customized_pricing;
                                                                                            } else {
          console.error(res.error);
        }
      });
    };
                                            //获取标签列表
    let get_list_customization_requirements = async () => {
      let json = await $get("/api/classification_information/get_list");
      if (json.result && json.result.list) {
        list_customization_requirements.value = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
    }
                    let select_customization_requirements_multiple = (v) => {
      form.value.customization_requirements = "";
      if (v && v.length > 0) {
        form.value.customization_requirements = v.toString();
      }
    };
                                                                    // 富文本编辑器更新
    let update_product_details = (obj) => {
        form.value.product_details = obj;
    };
    let blur_product_details = (obj) => {
        form.value.product_details = obj;
    };
                        // 上传二维码
    let upload_qrcode = (param) => {
      uploadFile(param.file, "qrcode_img");
    };
        /**
    * 上传封面图
    * @param {Object} file 文件对象
    * @param {key} 保存键名
    */
    const uploadFile = (file, key = "img") => {
        var formobj = new FormData(); // FormData 对象
        formobj.append("file", file); // 文件对象
              $upload(url_upload.value, formobj, function (json) {
          if (json.result) {
            form.value[key] = json.result.url;
          } else {
            ElMessage.error("上传失败！");
          }
        });
    };
    /**
     * 上传文件
     * @param {String} url 请求地址
     * @param {Object} body 请求参数
     * @param {Funciton} func 回调函数，可以为空，为空则采用await返回值
     * @return {Object} 返回请求结果
     */
    let $upload = async (url, body, func) => {
      url = url.replace("~/", $banseUrl);

      if (func) {
        // 如果回调函数存在, 则采用异步
              $post(url, body, {
          headers: {
            "x-auth-token": token,
            "Content-Type": "multipart/form-data",
          },
        })
            .then((res) => {
              func(res);
            })
            .catch((res) => {
              func(res);
            });
      } else {
        // 否则采用同步
        var res = await $post(url, body, {
          headers: {
            "x-auth-token": token,
            "Content-Type": "multipart/form-data",
          },
        });
        return res;
      }
    };
    let getLongitudeLatitude = () => {
      form.value.location_address = "广东省深圳市南山区科技园";
      form.value.location_lng = "113.946782";
      form.value.location_lat = "22.556481";
      //如果该对象存在，那么地理位置服务可用。
      if ("geolocation" in navigator) {
        /* 地理位置服务可用 */
        let options = {
          enableHighAccuracy: true, //布尔值，表示系统是否使用最高精度来表示结果，注意，这会导致较慢的响应时间或者增加电量消耗（比如对于支持gps的移动设备来说）。如果值为false ，设备会通过更快响应以及/或者使用更少的电量等方法来尽可能的节约资源。默认值fasle
          timeout: 5000, //它表明的是设备必须在多长时间（单位毫秒）内返回一个位置。默认直到获取到位置才会返回值。
          maximumAge: 0, //表明可以返回多长时间（即最长年龄，单位毫秒）内的可获取的缓存位置。如果设置为 0, 说明设备不能使用一个缓存位置，而且必须去获取一个真实的当前位置。默认0
        };
        function success(position) {
          //position.coords (只读) 返回一个定义了当前位置的Coordinates对象。
          //position.timestamp (只读) 返回一个时间戳DOMTimeStamp， 这个时间戳表示获取到的位置的时间。
          let lat = position.coords.latitude; //当前位置的纬度
          let lng = position.coords.longitude; //当前位置精度
          let location = lng + "," + lat;
          let url =
              "http://restapi.amap.com/v3/geocode/regeo?key=b6eb2819a6ba4c5119591614272fe7ca&location=" +
              location;
                $get(url).then((res) => {
            if (res.status === 200) {
              let data = res.data;
              if (data.status === "1") {
                form.value.location_address = data.regeocode.formatted_address;
                form.value.location_lng = JSON.stringify(lng);
                form.value.location_lat = JSON.stringify(lat);
              } else {
                console.log(data.info);
              }
            }
          })
              .catch((res) => {
                console.log(res);
              });
        }
        function error(err) {
          let errorType = [
            "您拒绝共享位置信息",
            "获取不到位置信息",
            "获取位置信息超时",
          ];
          console.log(errorType[err.code - 1]);
        }
        navigator.geolocation.getCurrentPosition(success, error, options);
      } else {
        /* 地理位置服务不可用 */
        console.log("无法获取您的位置，请检查定位是否开启或刷新重试");
      }
    };
  //提交前验证事件
  let submit_check = () => {
                                                      if (!param.production_date){
      return "生产日期不能为空";
    }
                      if (!param.shelf_life){
      return "保质时间不能为空";
    }
                                                          };
  // 点击取消
  let cancel = () => {
    router.go(-1);
  };
  // 点击提交
  let onSubmit = async () => {
    let valid = await ruleFormRef.value.validate();
    if (valid) {
      // 提交表单
      if (customized_products_id) {
        // 编辑
        delete form.value.update_time;
              $post(url_set.value + "?customized_products_id=" + customized_products_id, form.value).then((res) => {
          if (res.result) {
          router.push("/home/customized_products/table");
          ElMessage.success("提交成功！");
          } else if (res.error) {
            ElMessage.error(res.error.message);
          }
        });

      } else {
        // 新增
              $post(url_add.value, form.value).then((res) => {
          if (res.result) {
              router.push("/home/customized_products/table");
              ElMessage.success("提交成功！");
          } else if (res.error) {
            ElMessage.error(res.error.message);
          }
        });

      }
    } else {
      ElMessage.error(msg);
    }
  };
  // 查询数组对象某个是否包含某个值,返回对应对象
  let getObj = (arr, val) => {
    let obj = arr.find((item) => item.user_id == val);
    let ret = "";
    if (obj) {
      if (obj.nickname) {
        ret = obj.nickname;
      } else {
        ret = obj.username;
      }
    }
    return ret;
  };
  //获取对象之前
  let get_obj_before = (param) => {
    var formArr = "";
                                  if(form.value && formArr){
      Object.keys(form.value).forEach(key => {
        Object.keys(formArr).forEach(dbKey => {
          if(key === dbKey){
            disabledObj.value[key+'_isDisabled'] = true;
          }
        })
      })
    }
                                if (form.value["production_date"] && isTimestamp(form.value["production_date"])) {
      form.value["production_date"] = $toTime(parseInt(form.value["production_date"]), "YYYY-MM-DD")
    }
            if (form.value["shelf_life"] && isTimestamp(form.value["shelf_life"])) {
      form.value["shelf_life"] = $toTime(parseInt(form.value["shelf_life"]), "YYYY-MM-DD HH:mm:ss")
    }
                                localStorage.removeItem('form')
    return param;
  }
  // js判断字段是否是时间戳格式
  let isTimestamp = (value) => {
    return /^\d{10}$/.test(value) || /^\d{13}$/.test(value);
  }
  //获取对象之后
  let get_obj_after = (json, func) => {
                                                                                                                                                                                                      if (form.value["production_date"] == "0000-00-00") {
            form.value["production_date"] = null;
          }
          if (parseInt(form.value["production_date"]) > 9999) {
            form.value["production_date"] = $toTime(parseInt(form.value["production_date"]), "YYYY-MM-DD")
          }
                                                                  if (form.value["shelf_life"] == "0000-00-00 00:00:00") {
            form.value["shelf_life"] = null;
          }
          if (parseInt(form.value["shelf_life"]) > 9999) {
            form.value["shelf_life"] = $toTime(parseInt(form.value["shelf_life"]), "YYYY-MM-DD HH:mm:ss")
          }
                                                                                                                      if (form.value.customization_requirements){
                  customization_requirements_multiple_value = form.value.customization_requirements.split(",")
          }
                                                                                                          if (form.value["timing_end_time"] && JSON.stringify(form.value["timing_end_time"]).indexOf("-") === -1) {
        form.value["timing_end_time"] = $toTime(parseInt(form.value["timing_end_time"]),"YYYY-MM-DD HH:mm:ss");
      }
      if (form.value["timing_start_time"] && JSON.stringify(form.value["timing_start_time"]).indexOf("-") === -1) {
        form.value["timing_start_time"] = $toTime(parseInt(form.value["timing_start_time"]),"YYYY-MM-DD HH:mm:ss");
      }
      }
  let is_view = () => {
    var bl = user_group == "管理员";
    if (!bl) {
      bl = $check_action('/customized_products/table', 'add');
      console.log(bl ? "你有表格添加权限视作有添加权限" : "你没有表格添加权限");
    }
    if (!bl) {
      bl = $check_action('/customized_products/table', 'set');
      console.log(bl ? "你有表格添加权限视作有修改权限" : "你没有表格修改权限");
    }
    if (!bl) {
      bl = $check_action('/customized_products/view', 'add');
      console.log(bl ? "你有视图添加权限视作有添加权限" : "你没有视图添加权限");
    }
    if (!bl) {
      bl = $check_action('/customized_products/view', 'set');
      console.log(bl ? "你有视图修改权限视作有修改权限" : "你没有视图修改权限");
    }
    if (!bl) {
      bl = $check_action('/customized_products/view', 'get');
      console.log(bl ? "你有视图查询权限视作有查询权限" : "你没有视图查询权限");
    }
    console.log(bl ? "具有当前页面的查看权，请注意这不代表你有字段的查看权" : "无权查看当前页，请注意即便有字段查询权限没有页面查询权限也不行");
    return bl;
  }
  // 获取详情
  let get_customized_products_obj = async () => {
    let list = await $get("/api/customized_products/get_obj?customized_products_id=" + customized_products_id);
    form.value = list.result.obj;
    get_obj_after();
  };
  onMounted(() => {
              get_list_classification_name();
                            get_list_user_merchant_users();
          get_group_user_merchant_users();
                      get_list_customized_types();
          get_list_customization_requirements();
                    if (customized_products_id) {
      get_customized_products_obj();
    }else {
      get_obj_before();
      get_obj_after();
    }

  });
</script>

<style scoped lang="less">
  .diy_edit {
    width: 100%;

    .edit_customized_products_form {
      max-width: 80%;
      margin: 90px auto;

      .fn {
        width: 100%;
      }
    }

    img {
      width: 100px;
      height: 100px;
    }

    .edit_list_customized_products_sell {
      width: 80%;
      margin: 90px auto;
    }

    .footer {
      text-align: center;
    }
  }
</style>
  